package xyz.yang.toodles.statemachine;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Xuehong Yang
 * @since 1.0
 */
public class StateMachine<S extends State, E extends Event> {
    private final Map<StateEventPair<S, E>, S> stateEventPairs = new HashMap<>();

    /**
     * 定义状态机流转
     *
     * @param sourceState 源状态
     * @param event        事件
     * @param targetState 目标状态
     */
    public void config(S sourceState, E event, S targetState) {
        stateEventPairs.put(new StateEventPair<>(sourceState, event), targetState);
    }

    /**
     * 通过源状态和事件获取目标状态
     *
     * @param sourceState 源状态
     * @param event        事件
     * @return 目标状态
     */
    public S getTargetState(S sourceState, E event) {
        S targetState = stateEventPairs.get(new StateEventPair<>(sourceState, event));
        if (Objects.isNull(targetState)) {
            throw new IllegalStateException("状态迁移失败！(" + sourceState + "-" + event + ")");
        }
        return targetState;
    }
}
